import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.junit.Test;

/**
 * @author lemon
 * @version V1.0
 * @date 2020/08/31
 */
public class IndexDemo {


    RestHighLevelClient client = ESClient.getClient();

    private String index = "user-index";
    private String type = "user-type";

    /**
     * 创建索引，并指定settings和mappings
     */
    @Test
    public void test1() throws Exception {
        /**
         *   "settings": {
         *     "number_of_shards": 5,
         *     "number_of_replicas": 1
         *   }
         */
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 5)
                .put("number_of_replicas", 1);

        XContentBuilder mappings = JsonXContent.contentBuilder()
                .startObject()  // {
                .startObject("properties")    // "properties : {
                .startObject("user_id")      // "user_id": {
                .field("type", "keyword")   //"type":"keyword"
                .endObject()                 // }
                .startObject("username")      // "user_id": {
                .field("type", "text")   //"type":"keyword"
                .field("analyzer", "ik_max_word")
                .field("index", true)
                .field("store", true)
                .endObject()                 // }
                .startObject("email")      // "user_id": {
                .field("type", "keyword")
                .endObject()
                .startObject("address")
                .field("type", "text")
                .field("analyzer", "ik_max_word")
                .endObject()
                .startObject("birthday")
                .field("type", "date")
                .field("format", "yyyy-MM-dd")
                .endObject()
                .endObject()                    // }
                .endObject();   // }

        //创建索引请求
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index)
                .settings(settings)
                .mapping(type,mappings);
        //创建索引
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.isAcknowledged());

    }
}